/*
 * Copyright [2022] [liufeng]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.f.service.impl;

import com.f.base.Result;
import com.f.constant.ProcessConstants;
import com.f.enums.FlowComment;
import com.f.service.FlowDefinitionService;
import com.f.utils.ServiceUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.repository.ProcessDefinitionQuery;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;

/**
 * 流程定义
 *
 * @author liuf
 * @date 2022-12-09
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class FlowDefinitionServiceImpl implements FlowDefinitionService {

    private final ProcessEngine processEngine;

    @Override
    public boolean exist(String processDefinitionKey) {
        ProcessDefinitionQuery processDefinitionQuery
                = processEngine.getRepositoryService().createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey);
        long count = processDefinitionQuery.count();
        return count > 0;
    }

    /**
     * 根据流程定义ID启动流程实例
     *
     * @param procDefId 流程定义Id
     * @param variables 流程变量
     * @return 启动结果
     */
    @Override
    public Result<String> startProcessInstanceById(String procDefId, Map<String, Object> variables) {
        try {
            ProcessDefinition processDefinition = processEngine.getRepositoryService().createProcessDefinitionQuery().processDefinitionId(procDefId)
                    .latestVersion().singleResult();
            if (Objects.nonNull(processDefinition) && processDefinition.isSuspended()) {
                return Result.fail("流程已被挂起,请先激活流程");
            }
//           variables.put("skip", true);
//           variables.put(ProcessConstants.FLOWABLE_SKIP_EXPRESSION_ENABLED, true);
            // 设置流程发起人Id到流程中
            processEngine.getIdentityService().setAuthenticatedUserId(String.valueOf(ServiceUtils.getUserId()));
            variables.put(ProcessConstants.PROCESS_INITIATOR, "");
            ProcessInstance processInstance = processEngine.getRuntimeService().startProcessInstanceById(procDefId, variables);
            // 给第一步申请人节点设置任务执行人和意见 todo:第一个节点不设置为申请人节点有点问题？
            Task task = processEngine.getTaskService().createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
            if (Objects.nonNull(task)) {
                processEngine.getTaskService().addComment(task.getId(), processInstance.getProcessInstanceId(),
                        FlowComment.NORMAL.getType(), ServiceUtils.getSysUser().getName() + "发起流程申请");
//                processEngine.getTaskService().setAssignee(task.getId(), sysUser.getUserId().toString());
                processEngine.getTaskService().complete(task.getId(), variables);
            }
            return Result.success("流程启动成功");
        } catch (Exception e) {
            log.error("startProcessInstanceById", e);
            return Result.fail("流程启动错误");
        }
    }


    /**
     * 激活或挂起流程定义
     *
     * @param state    状态
     * @param deployId 流程部署ID
     */
    @Override
    public void updateState(Integer state, String deployId) {
        ProcessDefinition processDefinition = processEngine.getRepositoryService().createProcessDefinitionQuery().deploymentId(deployId).singleResult();
        // 激活
        if (state == 1) {
            processEngine.getRepositoryService().activateProcessDefinitionById(processDefinition.getId(), true, null);
        }
        // 挂起
        if (state == 2) {
            processEngine.getRepositoryService().suspendProcessDefinitionById(processDefinition.getId(), true, null);
        }
    }


    /**
     * 删除流程定义
     *
     * @param deployId 流程部署ID act_ge_bytearray 表中 deployment_id值
     */
    @Override
    public void delete(String deployId) {
        // true 允许级联删除 ,不设置会导致数据库外键关联异常
        processEngine.getRepositoryService().deleteDeployment(deployId, true);
    }

}
